<template>
  <div class="ai-mistakes-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-area">
      <div class="filter-header">
        <h2 class="ai-title">Bingo</h2>
        <div class="filter-newchat">
          <button class="modern-newchat-btn" @click="startNewChat">
            <svg class="modern-icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="3" y="11" width="18" height="2" rx="1" fill="#fff"/>
              <rect x="11" y="3" width="2" height="18" rx="1" fill="#fff"/>
            </svg>
            <span class="modern-text">新对话</span>
          </button>
        </div>
      </div>

      <div class="filter-content">
        <!-- 课程+知识点级联选择 -->
        <div class="filter-row">
          <div class="filter-label">课程与知识点</div>
          <el-cascader
            v-model="selectedCourseAndKnowledge"
            :options="courseKnowledgeOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择课程和知识点"
            class="filter-input"
          />
        </div>
        <div class="filter-actions filter-actions-large" style="margin-top: 18px;">
          <el-button type="primary" plain size="large" @click="handleFilter">
            <el-icon><Search /></el-icon> 筛选
          </el-button>
          <el-button plain size="large" @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </div>
        <!-- 掌握状态筛选已移除 -->
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧错题列表 -->
      <div class="questions-panel">
        <div class="panel-header">
          <h3>筛选结果 ({{ filteredQuestions.length }} 道)</h3>
        </div>
        <div class="questions-list">
          <div 
            v-for="(question, index) in filteredQuestions" 
            :key="index" 
            class="question-item"
            :class="{ selected: selectedQuestionIndex === index }"
            @click="selectQuestion(index)"
          >
            <div class="question-text" v-html="question.questionContent"></div>
            <!-- <div class="question-meta">
              <el-tag :type="question.isMastered ? 'success' : 'danger'" size="small">
                {{ question.isMastered ? '已掌握' : '未掌握' }}
              </el-tag>
              <span class="wrong-count">
                <el-icon><Warning /></el-icon> {{ question.wrongCount }}次
              </span>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 右侧AI聊天区域 -->
      <div class="chat-area">
        <div class="messages-container">
          <div 
            v-for="(message, index) in messages" 
            :key="index" 
            class="message"
            :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
          >
            <template v-if="message.role === 'user'">
              <div class="message-content" v-html="message.content"></div>
              <div class="message-avatar user-avatar-absolute">
                <img :src="userStore.getAvatar" alt="user" class="avatar-img" />
              </div>
            </template>
            <template v-else>
              <div class="message-content" v-html="message.content"></div>
            </template>
          </div>
        </div>
        <div class="input-area">
          <textarea 
            v-model="userInput" 
            placeholder="输入你的问题或从左侧选择错题..." 
            @keydown.enter.exact.prevent="sendMessage"
          ></textarea>
          <button class="send-btn" @click="sendMessage">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import type { CascaderProps } from 'element-plus'
import {
  Search,
  Refresh,
  Warning
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

// 课程、知识点、错题数据
const courseKnowledgeOptions = ref<any[]>([])
const cascaderProps: CascaderProps = {
  checkStrictly: true,
  expandTrigger: 'hover'
}

// 新对话按钮逻辑
const startNewChat = () => {
  messages.value = [];
  userInput.value = '';
  selectedQuestionIndex.value = null;
};

// 筛选表单数据
const selectedCourseAndKnowledge = ref([])

// 错题数据
const allQuestions = ref<any[]>([])
const filteredQuestions = ref<any[]>([])
const selectedQuestionIndex = ref<number | null>(null)

// 用户信息
const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId)

// 聊天数据
const messages = ref<any[]>([])
const userInput = ref('')

// 添加一个ref来存储当前选中的错题信息
const currentQuestion = ref<any>(null)

// 课程、知识点初始化
const fetchCoursesAndPoints = async () => {
  const courseRes = await axios.get('http://localhost:8080/Courses/all')
  const courses = courseRes.data
  const cascaderData = await Promise.all(
    courses.map(async (course: any) => {
      const kpRes = await axios.get('http://localhost:8080/KnowledgePoint/course', { 
        params: { courseId: course.courseId } 
      })
      return {
        value: course.courseId,
        label: course.courseName,
        children: kpRes.data.map((kp: any) => ({
          value: kp.pointId,
          label: kp.pointName
        }))
      }
    })
  )
  courseKnowledgeOptions.value = cascaderData
}

// 查询错题
const fetchWrongQuestions = async () => {
  let params: any = {
    userId: userId.value
  }
  
  if (selectedCourseAndKnowledge.value.length > 0) {
    params.courseId = selectedCourseAndKnowledge.value[0]
    if (selectedCourseAndKnowledge.value.length > 1) {
      params.pointId = selectedCourseAndKnowledge.value[1]
    }
  }
  


  try {
    const res = await axios.get('http://localhost:8080/wrongquestions/query', { params })
    allQuestions.value = res.data.records
    filteredQuestions.value = res.data.records
  } catch (error) {
    ElMessage.error('获取错题失败')
    console.error(error)
  }
}

// 筛选按钮
const handleFilter = () => {
  fetchWrongQuestions()
}

// 重置按钮
const handleReset = () => {
  selectedCourseAndKnowledge.value = []
  fetchWrongQuestions()
}

// 选择错题
const selectQuestion = (index: number) => {
  selectedQuestionIndex.value = index
  const question = filteredQuestions.value[index]
  
  // 保存当前选中的错题信息，用于发送到后端
  currentQuestion.value = {
    questionContent: question.questionContent,
    answer: question.answer || '',
    analysis: question.analysis || ''
  }
  
  // 构建发送给AI的问题，包含题目、答案和解析
  userInput.value = `关于以下错题的问题:\n\n题目: ${question.questionContent}\n\n答案: ${question.answer || '（暂无答案）'}\n\n解析: ${question.analysis || '（暂无解析）'}\n\n所属课程: ${question.courseName}\n知识点: ${question.pointName}\n\n请详细解释这个题目并给出正确答案的分析过程`
}

// 发送消息给AI
const sendMessage = async () => {
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入问题')
    return
  }
  
  console.log('=== 开始发送消息到AI ===')
  console.log('用户输入:', userInput.value)
  
  const newMessage = { role: 'user', content: userInput.value }
  messages.value.push(newMessage)
  const currentInput = userInput.value
  userInput.value = ''
  
  try {
    // 添加AI思考的提示消息
    messages.value.push({ role: 'assistant', content: 'AI正在思考中...' })
    
    // 构建符合后端接口要求的请求数据
    const requestData = {
      questionContent: currentQuestion.value ? currentQuestion.value.questionContent : currentInput,
      answer: currentQuestion.value ? currentQuestion.value.answer : '',
      analysis: currentQuestion.value ? currentQuestion.value.analysis : ''
    }
    
    console.log('准备发送到后端的请求数据:', requestData)
    
    // 调用后端AI解释接口
    console.log('开始调用后端AI解释接口...')
    const response = await axios({
      method: 'post',
      url: 'http://localhost:8080/api/question/explain',
      data: requestData,
      headers: {
        'Content-Type': 'application/json'
      }
    })
    console.log('收到后端响应:', response.data)

    if (response.data && response.data.explanation) {
      // 移除思考提示消息
      messages.value = messages.value.filter(msg => msg.content !== 'AI正在思考中...')
      
      // 格式化并添加AI解释
      console.log('开始格式化AI响应...')
      const formattedContent = formatAIResponse(response.data.explanation)
      console.log('格式化后的内容:', formattedContent)
      
      messages.value.push({ 
        role: 'assistant', 
        content: formattedContent
      })
      console.log('消息已添加到对话列表')
    } else {
      console.warn('后端返回数据格式异常:', response.data)
      ElMessage.warning('获取AI解析失败')
    }
  } catch (error) {
    console.error('调用AI解释接口失败:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      console.error('错误状态码:', error.response.status)
    }
    ElMessage.error('获取AI解析失败')
    // 移除思考提示消息
    messages.value = messages.value.filter(msg => msg.content !== 'AI正在思考中...')
    messages.value.push({ 
      role: 'assistant', 
      content: '抱歉，获取AI解析失败，请稍后重试。'
    })
  }
}

// 格式化AI响应
const formatAIResponse = (content: string) => {
  // 处理标题
  content = content.replace(/### (.*?)(?=###|$)/gs, '<h3 class="ai-title">$1</h3>')
  
  // 处理加粗文本
  content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理代码块
  content = content.replace(/```(.*?)```/gs, '<pre class="ai-code-block">$1</pre>')
  
  // 处理表格
  content = content.replace(/\|(.*?)\|/g, (match) => {
    const cells = match.split('|').filter(cell => cell.trim())
    return `<td>${cells.join('</td><td>')}</td>`
  })
  content = content.replace(/\|(.*?)\|/g, '<tr>$&</tr>')
  content = content.replace(/<tr><td>(.*?)<\/td><\/tr>/g, '<table class="ai-table">$&</table>')
  
  // 处理列表
  content = content.replace(/- (.*?)(?=\n|$)/g, '<li class="ai-list-item">$1</li>')
  content = content.replace(/<li class="ai-list-item">(.*?)<\/li>/g, '<ul class="ai-list">$&</ul>')
  
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  return content
}

// 初始化
onMounted(() => {
  fetchCoursesAndPoints()
  if (userId.value) {
    fetchWrongQuestions()
  } else {
    const stop = watch(userId, (val) => {
      if (val) {
        fetchWrongQuestions()
        stop()
      }
    })
  }
})
</script>

<style scoped lang="scss">
.ai-mistakes-container {
  display: flex;
  flex-direction: column;
  min-height: 400px;
  height: 92vh;
  max-height: 100vh;
  background-color: #f5f7fa;
}

.filter-area {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px 20px;
  margin: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  
.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  flex-wrap: wrap;
  position: relative;
}
.filter-newchat {
  margin-left: 16px;
  display: flex;
  align-items: center;
  position: absolute;
  right: 0;
  /* 纵向与重置按钮对齐 */
  top: 82px;
}
  .ai-title {
    margin: 0;
    font-size: 34px;
    color: #4f66cb;
    font-weight: 900;
    letter-spacing: 2.5px;
    font-family: 'Comic Sans MS', 'Chalkboard SE', 'Bebas Neue', 'Oswald', 'Impact', 'Arial Black', 'Segoe UI', '微软雅黑', 'Arial', sans-serif;
    text-shadow: 0 4px 16px #b3c6ff, 0 1px 0 #fff;
    text-transform: uppercase;
    border-radius: 18px;
    background: linear-gradient(90deg, #f9f8f9 0%, #e3f0ff 100%);
    display: inline-block;
    padding: 6px 32px 6px 24px;
    position: relative;
  }
  .ai-title::after {
    content: '✨';
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%) rotate(-10deg);
    font-size: 1.3em;
    animation: sparkle 1.2s infinite alternate;
  }
  @keyframes sparkle {
    0% { filter: brightness(1) drop-shadow(0 0 0 #fff); }
    100% { filter: brightness(1.5) drop-shadow(0 0 8px #fff6); }
  }

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Oswald:wght@700&display=swap');
  .filter-actions-large {
    margin-top: 10px;
    gap: 10px;
    .el-button {
      min-width: 80px;
      height: 40px;
      font-size: 14px;
      padding: 0 px;
      border-radius: 10px;
    }
  }
}

.el-button.my-large-btn {
  min-width: 100px;
  height: 10px;
  font-size: 16px;
}

  .filter-content {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
  }
  
  .filter-row {
    display: flex;
    align-items: center;
    
    .filter-label {
      width: 80px;
      font-size: 14px;
      color: #606266;
      white-space: nowrap;
      margin-right: 10px;
    }
    
    .filter-input {
      flex: 1;
      min-width: 500px;
      max-width: 520px;
      font-size: 18px;
      height: 48px;
      // 放大el-cascader内部输入框
      :deep(.el-input__wrapper),
      :deep(.el-input__inner) {
        min-height: 48px;
        font-size: 18px;
        padding: 0 18px;
      }
    }
  }


.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  margin: 10px;
  gap: 16px;
  border-radius: 32px;
  position: relative;
  box-shadow: 0 8px 32px 0 rgba(99, 143, 255, 0.10);
  background: #fafdff;
  z-index: 1;
  // 可爱气泡背景
  &::before {
    content: '';
    position: absolute;
    left: 10%;
    top: 10%;
    width: 80px;
    height: 80px;
    background: radial-gradient(circle at 30% 30%, #e3f0ff 60%, transparent 100%);
    border-radius: 50%;
    z-index: 0;
    opacity: 0.5;
  }
  &::after {
    content: '';
    position: absolute;
    right: 8%;
    bottom: 8%;
    width: 60px;
    height: 60px;
    background: radial-gradient(circle at 70% 70%, #ffe3f0 60%, transparent 100%);
    border-radius: 50%;
    z-index: 0;
    opacity: 0.4;
  }
}

.questions-panel {
  width: 300px;
  background-color: #fff;
  border-radius: 28px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 24px 0 rgba(99, 143, 255, 0.10);
  position: relative;
  z-index: 1;
  
  .panel-header {
    padding: 20px 16px 12px 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
    gap: 8px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      color: #333;
      font-family: 'Bebas Neue', 'Oswald', 'Comic Sans MS', cursive;
      letter-spacing: 1.5px;
    }
    // 可爱icon
    &::before {
      content: '🐾';
      font-size: 1.5em;
      margin-right: 6px;
      display: inline-block;
    }
  }
  
  .questions-list {
    flex: 1;
    overflow-y: auto;
    padding: 12px 8px 8px 8px;
  }
  
  .question-item {
    padding: 14px 14px 14px 18px;
    margin-bottom: 12px;
    border-radius: 18px 28px 18px 28px;
    cursor: pointer;
    transition: background-color 0.2s, box-shadow 0.2s;
    border: 1.5px solid #e0e0e0;
    background: #fafdff;
    box-shadow: 0 2px 8px 0 rgba(99, 143, 255, 0.06);
    position: relative;
    
    &:hover {
      background-color: #f5f5f5;
      box-shadow: 0 4px 16px 0 rgba(99, 143, 255, 0.10);
    }
    
    &.selected {
      background-color: #e8f0fe;
      border-color: #aac8ff;
    }
    
    .question-text {
      font-size: 15px;
      line-height: 1.5;
      margin-bottom: 8px;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .question-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #666;
    }
    // 可爱小icon
    &::after {
      content: '✨';
      position: absolute;
      right: 12px;
      top: 12px;
      font-size: 1.1em;
      opacity: 0.7;
      pointer-events: none;
    }
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 32px;
  box-shadow: 0 4px 24px 0 rgba(99, 143, 255, 0.10);
  position: relative;
  z-index: 1;
  
  // 顶部可爱icon
  &::before {
    content: '😺';
    position: absolute;
    left: 32px;
    top: 10px;
    font-size: 2.1em;
    z-index: 2;
    opacity: 0.85;
    pointer-events: none;
  }
  
  .messages-container {
    flex: 1;
    padding: 24px 24px 12px 24px;
    overflow-y: auto;
    
    .message {
      display: flex;
      align-items: flex-start;
      margin-bottom: 18px;
      max-width: 80%;
      position: relative;
      z-index: 1;
    }
    
    .message-avatar {
      width: 38px;
      height: 38px;
      margin-right: 12px;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .avatar-img {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      object-fit: cover;
      box-shadow: 0 2px 8px 0 rgba(99, 143, 255, 0.10);
      border: 2px solid #fff;
      background: #fafdff;
    }
    
    .message-content {
      padding: 14px 20px;
      border-radius: 18px 24px 18px 24px;
      line-height: 1.7;
      font-size: 15px;
      box-shadow: 0 2px 8px 0 rgba(99, 143, 255, 0.06);
      position: relative;
      background: #f1f3f4;
      color: #202124;
    }
    
    .user-message {
      position: relative;
      flex-direction: row;
      margin-left: auto;
      .message-content {
        background-color: #1a73e8;
        color: white;
        border-top-right-radius: 0;
        border-bottom-right-radius: 32px;
        margin-right: 48px; /* 头像空间同步缩小 */
      }
      .user-avatar-absolute {
        position: absolute;
        right: 2px; /* 距离聊天框更近一点 */
        top: 0;
        margin: 0;
        z-index: 2;
      }
    }
    .ai-message {
      flex-direction: row;
      margin-right: auto;
      .message-avatar {
        margin-right: 12px;
        margin-left: 0;
        position: static;
      }
      .message-content {
        background-color: #f1f3f4;
        color: #202124;
        border-top-left-radius: 0;
        border-bottom-left-radius: 32px;
      }
    }
  }
  
  .input-area {
    padding: 18px 24px;
    border-top: 1.5px solid #e0e0e0;
    display: flex;
    gap: 10px;
    background: #fafdff;
    border-radius: 0 0 32px 32px;
    
    textarea {
      flex: 1;
      padding: 14px 18px;
      border: 1.5px solid #e0e0e0;
      border-radius: 24px;
      resize: none;
      height: 48px;
      max-height: 120px;
      font-size: 15px;
      outline: none;
      transition: border-color 0.2s;
      background: #fff;
      
      &:focus {
        border-color: #5b82b5;
      }
    }
    
    .send-btn {
      background: #fafafa;
      border: none;
      color: #67c7ea;
      cursor: pointer;
      padding: 10px;
      border-radius: 50%;
      transition: background-color 0.2s, color 0.2s;
      align-self: flex-end;
      font-size: 1.5em;
      box-shadow: 0 2px 8px 0 rgba(224, 108, 159, 0.10);
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:hover {
        background-color: #f1eec2;
        color: #d8c049;
      }
      // 可爱emoji
      &::after {
        margin-left: 4px;
        font-size: 1.1em;
      }
    }
  }
}

.modern-newchat-btn {
  background: linear-gradient(90deg, #4f8cff 0%, #bfe9ec 100%);
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  border: none;
  border-radius: 18px;
  box-shadow: 0 2px 12px 0 rgba(79, 140, 255, 0.13);
  padding: 10px 28px 10px 18px;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: background 0.2s, box-shadow 0.2s, color 0.2s, transform 0.1s;
  cursor: pointer;
  outline: none;
  letter-spacing: 1.5px;
}
.modern-newchat-btn:hover {
  background: linear-gradient(90deg, #38e8fa 0%, #4f8cff 100%);
  color: #fff;
  box-shadow: 0 6px 24px 0 rgba(56, 232, 250, 0.13);
  transform: translateY(-2px) scale(1.04);
}
.modern-icon {
  width: 24px;
  height: 24px;
  margin-right: 4px;
  display: flex;
  align-items: center;
}
.modern-text {
  font-family: 'Segoe UI', 'Arial', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-weight: 600;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .questions-panel {
    width: 100%;
    height: 300px;
  }
  
  .filter-content {
    grid-template-columns: 1fr !important;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: flex-start !important;
    
    .filter-label {
      margin-bottom: 8px;
      width: 100% !important;
    }
  }
}

.ai-title {
  color: #1a73e8;
  font-size: 1.2em;
  margin: 1em 0;
  font-weight: 600;
}

.ai-code-block {
  background-color: #f8f9fa;
  padding: 1em;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  margin: 1em 0;
  border: 1px solid #e0e0e0;
}

.ai-table {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  
  td {
    border: 1px solid #e0e0e0;
    padding: 8px;
    text-align: left;
  }
  
  tr:first-child td {
    background-color: #f5f5f5;
    font-weight: 600;
  }
}

.ai-list {
  list-style-type: none;
  padding-left: 1em;
  margin: 1em 0;
  
  .ai-list-item {
    position: relative;
    padding-left: 1.5em;
    margin-bottom: 0.5em;
    
    &:before {
      content: "•";
      position: absolute;
      left: 0;
      color: #1a73e8;
    }
  }
}

.filter-actions {
  display: flex;
  gap: 10px;
  width: 100%;
  
  .el-button {
    min-width: 100px;
    color: #606266;
    
    &.el-button--primary {
      color: white;
    }
    
    .el-icon {
      margin-right: 8px;
    }
  }
}
</style>